package edu.taru.service.impl;

import edu.taru.mapper.DepartmentMapper;
import edu.taru.pojo.Department;
import edu.taru.service.ExcelService;
import edu.taru.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ExcelServiceImpl implements ExcelService {

    private DepartmentMapper deptMapper;
    @Autowired
    public ExcelServiceImpl(DepartmentMapper deptMapper){
        this.deptMapper = deptMapper;
    }

    /**
     *
     * @param out
     * @throws IOException
     */
    @Override
    public ResponseEntity<byte[]> exportDeptExcel(ByteArrayOutputStream out) throws IOException {
        //先获得部门信息
        List<Department> data = deptMapper.listDepts();
        ExcelUtil.exportDeptExcel(data,out);

        HttpHeaders headers = new HttpHeaders();
        String fileName = new String(("部门信息表"+ LocalDateTime.now() +".xls").getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> filebyte = new ResponseEntity<byte[]>(out.toByteArray(),headers, HttpStatus.CREATED);
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return filebyte;
    }
}
